from PyQt5.QtWidgets import QApplication,QWidget,QLabel,QPushButton,QGridLayout,QLineEdit
from PyQt5.QtCore import Qt
import sys

class Window(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        # 屏幕
        self.screen = QLineEdit()
        # 设置屏幕为只读
        self.screen.setReadOnly(True)
        # 设置右对齐
        self.screen.setAlignment(Qt.AlignRight)

        # 按钮的标签
        labels = ['<——','C','','',
                  '7','8','9','/',
                  '4','5','6','*',
                  '1','2','3','-',
                  '0','.','=','+']
        # [(1,1),(1,2)]
        positions = [(i,j) for i in range(1,6) for j in range(1,5)]

        # 创建一个表格布局
        grid = QGridLayout()
        self.setLayout(grid)

        # 将屏幕添加到表格中
        grid.addWidget(self.screen,0,1,1,4)

        # 创建并添加按钮
        for label,position in zip(labels,positions):
            if label != '':
                # 创建按钮
                btn = QPushButton(label)
                # 给按钮绑定功能
                btn.clicked.connect(self.action)
                # 添加按钮到表格中
                # grid.addWidget(btn,position[0],position[1])
                grid.addWidget(btn,*position)

        self.setGeometry(1000,300,300,200)
        self.setWindowTitle('计算器')
        self.show()

    def action(self):
        '''对按钮进行分类'''
        # 获取按钮的标签
        label = self.sender().text()
        if label == '<——':
            self.backsapce()
        elif label == 'C':
            self.clear()
        elif label == '=':
            self.calculate()
        else:
            self.showmsg(label)

    def showmsg(self,label):
        '''将内容写入到屏幕中'''
        # 获取原有内容
        old = self.screen.text()
        # 判断最后一个字符是否是+-*/
        if len(old) != 0 and old[-1] in '+-*/' and label in '+-*/':
            exp = old[:-1]+label
        else:
            exp = old+label
        # 写入
        self.screen.setText(exp)

    def clear(self):
        '''清空屏幕内容'''
        self.screen.setText('')

    def backsapce(self):
        '''退格键'''
        # 获取原有内容
        old = self.screen.text()
        # 写入
        self.screen.setText(old[:-1])

    def calculate(self):
        try:
            # 获取表达式
            exp = self.screen.text()
            # 计算
            r = str(eval(exp))
        except:
            r = 'err.'
        finally:
            # 写入
            self.screen.setText(r)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = Window()
    app.exec()